/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/reverse-linked-list-ii
   @Language: C++
   @Datetime: 19-07-09 16:51
   */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode* reverseBetween(ListNode* head, int m, int n) {
		ListNode H(-1), *left, *right;
		for(n=n-m+1, H.next=head, left=&H; --m; left=left->next);
		for(right=NULL, head=left->next; n--; swap(head,right))
			swap(right,head->next);
		left->next->next=head;
		left->next=right;
		return H.next;
	}
};
